package com.hc.conferencecheck.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hc.conferencecheck.entity.*;
import com.hc.conferencecheck.mapper.AttendRecordMapper;
import com.hc.conferencecheck.mapper.ConferenceMapper;
import com.hc.conferencecheck.mapper.ConventionerMapper;
import com.hc.conferencecheck.service.MessageService;
import com.hc.conferencecheck.utils.MessageUtils;
import com.hc.conferencecheck.utils.VerificationCodeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 发送短信的service实现类
 */
//开启事务管理
@Transactional
@Service
@PropertySource(value = {"classpath:messageInfo.properties"}, encoding = "utf-8")
public class MessageServiceImpl implements MessageService {
    public static final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);
    @Autowired
    Environment environment;
    @Resource
    private AttendRecordMapper attendRecordMapper;
    @Resource
    private ConventionerMapper conventionerMapper;
    @Resource
    private ConferenceMapper conferenceMapper;

    /**
     * 给用户发送审核短信
     */
    public String sendApprovedMessage02(int attendRecordId, String templateParam) {
        AttendRecord attendRecord = attendRecordMapper.selectByPrimaryKey(attendRecordId);
        String statusCode = "";
        if (attendRecord != null) {
            //查询用户相关信息获取手机号
            Integer conventionerId = attendRecord.getConventionerId();
            Conventioner conventioner = conventionerMapper.selectByPrimaryKey(conventionerId);
            if (conventioner == null) {
                //排除与会记录中手机号为空的情况
                return "error";
            }
            String phoneNumber = conventioner.getPhoneNumber();

            //生成短信相关信息:短信签名，短信模板;
            String signature = environment.getProperty("signature");
            String template = environment.getProperty("approved_template02");
            //发送验证码,返回短信发送状态码
            statusCode = MessageUtils.sendMessage(phoneNumber, signature, template, templateParam);
        }
        return statusCode;
    }

    /**
     * 给用户发送审核未通过的短信
     */
    public String sendNotApprovedMessage(int attendRecordId, String reason) {
        AttendRecord attendRecord = attendRecordMapper.selectByPrimaryKey(attendRecordId);
        String statusCode = "";
        if (attendRecord != null) {
            //查询用户相关信息获取手机号
            Integer conventionerId = attendRecord.getConventionerId();
            Conventioner conventioner = conventionerMapper.selectByPrimaryKey(conventionerId);
            if (conventioner == null) {
                //排除与会记录中手机号为空的情况
                return "error";
            }
            String phoneNumber = conventioner.getPhoneNumber();

            Map<String, Object> param = new HashMap<>();
            param.put("reason", reason);
            String templateParam = JSONObject.toJSONString(param);

            //生成短信相关信息:短信签名，短信模板;
            String signature = environment.getProperty("signature");
            String template = environment.getProperty("notApproved_template");
            //发送验证码,返回短信发送状态码
            statusCode = MessageUtils.sendMessage(phoneNumber, signature, template, templateParam);
        }
        return statusCode;
    }

    /**
     * 给用户发送审核通过的短信
     */
    public String sendApprovedMessage(int attendRecordId) {
        AttendRecord attendRecord = attendRecordMapper.selectByPrimaryKey(attendRecordId);
        String statusCode = "";
        if (attendRecord != null) {
            //查询用户相关信息
            Integer conventionerId = attendRecord.getConventionerId();
            Conventioner conventioner = conventionerMapper.selectByPrimaryKey(conventionerId);
            if (conventioner == null) {
                //排除与会记录中手机号为空的情况
                return "error";
            }
            String phoneNumber = conventioner.getPhoneNumber();
            //查询会议相关信息
            Integer conferenceId = attendRecord.getConferenceId();
            Conference conference = conferenceMapper.selectByPrimaryKey(conferenceId);
            String name = conference.getName();
            String date = conference.getDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String dateStr = sdf.format(date);
            String site = conference.getSite();
            //给该手机号发送短信
            //对验证码进行参数格式化
            String templateParam = MessageUtils.formattemplateParamForApproved(name, dateStr, site);

            //生成短信相关信息:短信签名，短信模板;
            String signature = environment.getProperty("signature");
            String template = environment.getProperty("approved_template");
            //发送验证码,返回短信发送状态码
            statusCode = MessageUtils.sendMessage(phoneNumber, signature, template, templateParam);
        }
        return statusCode;
    }

    /**
     * 发送修改密码的短信验证码接口
     */
    public ResultMsg sendEditPasswordVerificationCode(Map<String, Object> params, HttpServletRequest request) {
        //获取手机号
        Object phoneNumberObj = params.get("phoneNumber");
        String phoneNumber = null;
        //校验手机号参数是否为空
        if (phoneNumberObj != null) {
            phoneNumber = phoneNumberObj.toString();
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号不可为空");
        }

        //生成验证码
        String verificationCode = VerificationCodeUtils.createVerificationCode();
        //对验证码进行参数格式化
        String templateParam = MessageUtils.formattemplateParamForRegister(verificationCode);

        //生成短信相关信息:短信签名，短信模板;
        String signature = environment.getProperty("signature");
        String template = environment.getProperty("edit_password_template");
        //发送验证码,返回短信发送状态码
        String statusCode = MessageUtils.sendMessage(phoneNumber, signature, template, templateParam);
        //根据短信回执状态码，判断是否发送成功
        if (statusCode != null && statusCode.equals("OK")) {
            //请求成功，将验证码放入session中，设置有效时间为1分钟
            HttpSession session = request.getSession();
            session.setAttribute(phoneNumber, verificationCode);

            //保存重置密码时验证码接收手机号,用于重置密码时的手机号是否一致的校验
            session.setAttribute("editPassword_code_phoneNumber", phoneNumber);

            session.setMaxInactiveInterval(300);
            //返回结果集
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "重置密码短信验证码发送成功");
        } else {
            logger.error("重置密码短信验证码发送失败,回执状态码：" + statusCode);
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "重置密码短信验证码发送失败");
        }
    }

    /**
     * 发送注册验证码接口
     */
    public ResultMsg sendRegisterVerificationCode(Map<String, Object> params, HttpServletRequest request) {
        //获取手机号
        Object phoneNumberObj = params.get("phoneNumber");
        String phoneNumber = null;
        //校验手机号参数是否为空
        if (phoneNumberObj != null) {
            phoneNumber = phoneNumberObj.toString();
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号不可为空");
        }

        //生成验证码
        String verificationCode = VerificationCodeUtils.createVerificationCode();
        //对验证码进行参数格式化
        String templateParam = MessageUtils.formattemplateParamForRegister(verificationCode);

        //生成短信相关信息:短信签名，短信模板;
        String signature = environment.getProperty("signature");
        String template = environment.getProperty("register_template");
        //发送验证码,返回短信发送状态码
        String statusCode = MessageUtils.sendMessage(phoneNumber, signature, template, templateParam);

        //存储当前发送时间，用于两次发送时间的比较（不论成功与否都要保存当前发送时间，即时发送失败，一分钟内也不允许再次发送）
//        long lastSendTime = System.currentTimeMillis() / 1000;
//        session.setAttribute("lastSendTime", lastSendTime);

        //根据短信回执状态码，判断是否发送成功
        if (statusCode != null && statusCode.equals("OK")) {
            HttpSession session = request.getSession();
            //请求成功，将验证码放入session中，设置有效时间为1分钟
            session.setAttribute(phoneNumber, verificationCode);

            //存储此次发送验证码的手机号，用于注册时判断发送验证码的手机号和注册的手机号是否一致；
            session.setAttribute("register_code_phoneNumber", phoneNumber);

            session.setMaxInactiveInterval(300);


            //返回结果集
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "注册短信验证码发送成功");
        } else {
            System.out.println("短信发送失败，回执状态码为：" + statusCode);
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "注册短信验证码发送失败");
        }
    }

    /**
     * 发送登录验证码接口
     */
    public ResultMsg sendLoginVerificationCode(Map<String, Object> params, HttpServletRequest request) {
        //获取手机号
        Object phoneNumberObj = params.get("phoneNumber");
        String phoneNumber = null;
        //校验手机号参数是否为空
        if (phoneNumberObj != null) {
            phoneNumber = phoneNumberObj.toString();
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号不可为空");
        }

        //生成验证码
        String verificationCode = VerificationCodeUtils.createVerificationCode();
        //对验证码进行参数格式化
        String templateParam = MessageUtils.formattemplateParamForRegister(verificationCode);

        //生成短信相关信息:短信签名，短信模板;
        String signature = environment.getProperty("signature");
        String template = environment.getProperty("login_template");
        //发送验证码,返回短信发送状态码
        String statusCode = MessageUtils.sendMessage(phoneNumber, signature, template, templateParam);
        //根据短信回执状态码，判断是否发送成功
        if (statusCode != null && statusCode.equals("OK")) {
            //请求成功，将验证码放入session中，设置有效时间为1分钟
            HttpSession session = request.getSession();
            session.setAttribute(phoneNumber, verificationCode);
            session.setMaxInactiveInterval(60);
            //返回结果集
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "登录短信验证码发送成功");
        } else {
            logger.error("登录短信验证码发送失败，回执码：" + statusCode);
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "登录短信验证码发送失败");
        }
    }
}
